import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/account/iview/account_summary_iview.dart';
import 'package:flutter_deer/account/iview/exist_withdraw_password_iview.dart';
import 'package:flutter_deer/account/models/account_summary_entity.dart';
import 'package:flutter_deer/account/presenter/account_summary_presenter.dart';
import 'package:flutter_deer/account/presenter/exist_withdraw_password_presenter.dart';
import 'package:flutter_deer/account/provider/account_summary_provider.dart';
import 'package:flutter_deer/account/widgets/rise_number_text.dart';
import 'package:flutter_deer/account/widgets/withdrawal_password_setting.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/click_item.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../account_router.dart';

class AccountPage extends StatefulWidget {

  const AccountPage({super.key});

  @override
  _AccountPageState createState() => _AccountPageState();
}

class _AccountPageState extends State<AccountPage> with BasePageMixin<AccountPage, PowerPresenter> implements AccountSummaryIMvpView,ExistWithdrawPasswordIMvpView {

  AccountSummaryProvider provider = AccountSummaryProvider();
  late AccountSummaryPagePresenter accountSummaryPagePresenter;
  late ExistWithdrawPasswordPresenter existWithdrawPasswordPresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    accountSummaryPagePresenter = new AccountSummaryPagePresenter();
    existWithdrawPasswordPresenter = new ExistWithdrawPasswordPresenter();
    powerPresenter.requestPresenter([accountSummaryPagePresenter,existWithdrawPasswordPresenter]);
    return powerPresenter;
  }

  @override
  void setAccountSummary(AccountSummaryEntity? entity){
    provider.setAccountSummary(entity);
  }

  @override
  void existWithdrawPassword(bool? result){
    provider.setExistWithdrawPassword(result);
  }

  @override
  void initState() {
    super.initState();
    if(mounted){
      Future.delayed(Duration(seconds: 1),()=>{accountSummaryPagePresenter.getAccountSummary()});
      Future.delayed(Duration(seconds: 1),()=>{existWithdrawPasswordPresenter.getExistWithdrawPassword()});
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '${DeerLocalizations.of(context)!.fundManagement.nullSafe}',
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Gaps.vGap5,
            _buildCard(),
            Gaps.vGap5,
          ChangeNotifierProvider<AccountSummaryProvider>(
            create: (_) => provider,
            child: Consumer<AccountSummaryProvider>(
              builder: (_, provider, child) {
                return provider.existWithdrawPasswordState==StateType.loading?ClickItem(title: '${DeerLocalizations.of(context)!.dataLoading.nullSafe}'):ClickItem(
                  title: '${DeerLocalizations.of(context)!.withdrawal.nullSafe}',
                  onTap: () {
                    if(provider.existWithdrawPassword==true) {
                      NavigatorUtils.pushResult(context, AccountRouter
                          .withdrawalPage, arguments: provider.accountSummary!
                          .allowTakeOutScore, (result) {
                        if (result != null && result == 'success') {
                          accountSummaryPagePresenter.getAccountSummary();
                        }
                      });
                    }else{
                      showModalBottomSheet<void>(
                          context: context,
                          /// 禁止拖动关闭
                          enableDrag: false,
                          /// 使用true则高度不受16分之9的最高限制
                          isScrollControlled: true,
                          builder: (_) => const WithdrawalPasswordSetting()
                      ).then((value) => {
                        Future.delayed(Duration(seconds: 1),()=>existWithdrawPasswordPresenter.getExistWithdrawPassword())
                      });
                    }
                  });
              }
            )
          ),
            ClickItem(
              title: '${DeerLocalizations.of(context)!.withdrawRecord.nullSafe}',
              onTap: () => NavigatorUtils.push(context, AccountRouter.takeoutPage),
            ),
            ChangeNotifierProvider<AccountSummaryProvider>(
                create: (_) => provider,
                child: Consumer<AccountSummaryProvider>(
                  builder: (_, provider, child) {
                    return Visibility(
                        visible: provider.existWithdrawPasswordState!=StateType.loading,
                        child: ClickItem(
                          title: '${DeerLocalizations.of(context)!.withdrawPassword.nullSafe}',
                          onTap: () => NavigatorUtils.push(context, AccountRouter.withdrawalPasswordPage),
                        )
                    );
                  }
                )
            ),
          ],
        ),
      )
    );
  }

  Widget _buildCard() {
    return ChangeNotifierProvider<AccountSummaryProvider>(
        create: (_) => provider,
        child: Consumer<AccountSummaryProvider>(
          builder: (_, provider, child) {
            if(provider.stateType==StateType.loading){
              return StateLayout(type: StateType.loading);
            }
            AccountSummaryEntity? accountSummaryEntity = provider.accountSummary;
            double? totalTakeOutScore = accountSummaryEntity!.totalTakeOutScore;
            double? totalGiveScore = accountSummaryEntity!.totalGiveScore;
            double? currentScore = accountSummaryEntity!.currentScore;
            double? freezeScore = accountSummaryEntity!.freezeScore;
            return AspectRatio(
              aspectRatio: 1.85,
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 6.0),
                padding: const EdgeInsets.all(6.0),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: ImageUtils.getAssetImage('account/bg'),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Column(
                  children: <Widget>[
                    _AccountMoney(
                      title: '${DeerLocalizations.of(context)!.balance.nullSafe}',
                      money: currentScore.toString(),
                      alignment: MainAxisAlignment.end,
                      moneyTextStyle: TextStyle(color: Colors.white, fontSize: 32.0, fontWeight: FontWeight.bold, fontFamily: 'RobotoThin'),
                    ),
                    Expanded(
                      child: Row(
                        children: <Widget>[
                          _AccountMoney(title: '${DeerLocalizations.of(context)!.settlement.nullSafe}', money: totalTakeOutScore.toString().nullSafe),
                          _AccountMoney(title: '${DeerLocalizations.of(context)!.giftAmount.nullSafe}', money: totalGiveScore.toString().nullSafe),
                          _AccountMoney(title: '${DeerLocalizations.of(context)!.freezeAmount.nullSafe}', money: freezeScore.toString().nullSafe),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          }
        )
    );
  }
}

class _AccountMoney extends StatelessWidget {
  
  const _AccountMoney({
    required this.title,
    required this.money,
    this.alignment,
    this.moneyTextStyle
  });

  final String title;
  final String money;
  final MainAxisAlignment? alignment;
  final TextStyle? moneyTextStyle;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: MergeSemantics(
        child: Column(
          mainAxisAlignment: alignment ?? MainAxisAlignment.center,
          children: <Widget>[
            /// 横向撑开Column，扩大语义区域
            const SizedBox(width: double.infinity),
            Text(title, style: const TextStyle(color: Colours.text_disabled, fontSize: Dimens.font_sp12)),
            Gaps.vGap8,
            RiseNumberText(
              NumUtil.getDoubleByValueStr(money) ?? 0,
              style: moneyTextStyle ?? const TextStyle(
                color: Colours.text_disabled, 
                fontSize: Dimens.font_sp14,
                fontWeight: FontWeight.bold,
                fontFamily: 'RobotoThin'
              )
            ),
          ],
        ),
      ),
    );
  }
}
